package Servlet;

import Entity.Friends;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Clara
 */
public class PlayerAddServlet extends HttpServlet {

    @Resource
    private javax.transaction.UserTransaction utx;

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("resultString", addPlayers(request.getParameter("userName"), request.getParameter("friendName")));

        // Now that the controller has gathered the data from the model,
        // pass the data onto the view to render it as JSON.
        RequestDispatcher view = request.getRequestDispatcher("/add_delete_view.jsp");
        view.forward(request, response);
    }

    // to add a friend. Returns string to show whether it was successful.
    private String addPlayers(String userName, String friendName) {
        String addString = "";

        try {

            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");

            addString = "Adding";
            try {
                utx.begin();
                //make a new friend object
                Friends d = new Friends(userName, friendName);
                //merge object to entity manager
                d = em.merge(d);
                //persist object
                em.persist(d);
                //return a string to indicate friend added.
                addString = "Friend Added";
                utx.commit();
            } catch (Exception e) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
                throw new RuntimeException(e);

            }
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        return addString;
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
